<?php

namespace app\system\controller;

use app\common\model\ShopPromotionCardItemModel;
use app\common\model\ShopPromotionCardModel;
use app\common\model\ShopPromotionCardOrderModel;
use think\Request;

class ShopPromotionCardController extends BaseController
{

    private $cardModel;
    private $cardItemModel;
    private $cardOrderModel;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->cardModel = new ShopPromotionCardModel();
        $this->cardItemModel = new ShopPromotionCardItemModel();
        $this->cardOrderModel = new ShopPromotionCardOrderModel();
    }

    //列表
    public function index()
    {
        $map = [];
        $query = [];
        $siteId=$this->getSiteId();
        if ($siteId){
            $map['site_id']=$siteId;
        }
        $status = $this->request->param('status/d', 1);
        $query['status'] = $status;
        $title = $this->request->param('title');
        $query['title'] = $title;
        if (!empty($title)) {
            $map['title'] = ['like', '%' . $title . '%'];
        }
        $list = $this->cardModel->getPageList($status, $map, $query);
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }
    //列表
    public function lists()
    {
        $map = [];
        $query = [];
        $map['send_type']=2;
        $list = $this->cardModel->getPageList(1, $map, $query);
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }

    //添加
    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $result = $this->validate($data, 'ShopPromotionCardValidate');
            if (true !== $result) {
                $this->error($result);
            }
            if ($this->cardModel->addData($data)) {
                $this->success('添加成功！', url('index'));
            } else {
                $this->error($this->cardModel->getError());
            }
        }
        $this->assign('utype', $this->getUtype());
        return $this->fetch();
    }

    //编辑
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $result = $this->validate($data, 'ShopPromotionCardValidate');
            if (true !== $result) {
                $this->error($result);
            }
            if ($this->cardModel->editData($data)) {
                $this->success('添加成功！', url('index'));
            } else {
                $this->error($this->cardModel->getError());
            }
        }
        $cardId = $this->request->param('card_id/d');
        $info = $this->cardModel->find($cardId);
        $this->assign('info', $info);
        $this->assign('utype', $this->getUtype());
        return $this->fetch();
    }

    //删除
    public function del()
    {
        $cardId = $this->request->param('card_id/d', 0);
        $result = $this->cardModel->delData($cardId);
        if ($result === false) {
            $this->error($this->cardModel->getError());
        } else {
            $this->success('删除成功！');
        }
    }

    /**
     * 发放卡券
     */
    public function sendCardKey()
    {
        if ($this->request->isPost()) {
            $cardId = $this->request->param('card_id/d');
            $memberUids = $this->request->param('member_uids');
            if (empty($memberUids)) {
                $this->error('请先指定要发放得会员！');
            }
            $uids = explode(',', $memberUids);
            if (count($uids) > 180) {
                $this->error('对不起，一批次最多只可以发送180个会员！');
            }
            foreach ($uids as $uid) {
                $this->cardModel->sendCard($uid, $cardId);
            }
            $this->success('发送成功！');
        }
        return $this->fetch();
    }

    public function orderList()
    {
        $cardId = $this->request->param('card_id/d');
        $list = $this->cardOrderModel->where('card_id', $cardId)->paginate();
        $monthData = [date('Y') . '-01' => 0,
            date('Y') . '-02' => 0,
            date('Y') . '-03' => 0,
            date('Y') . '-04' => 0,
            date('Y') . '-05' => 0,
            date('Y') . '-06' => 0,
            date('Y') . '-07' => 0,
            date('Y') . '-08' => 0,
            date('Y') . '-09' => 0,
            date('Y') . '-10' => 0,
            date('Y') . '-11' => 0,
            date('Y') . '-12' => 0];
        $monthall = $this->cardOrderModel->cache(900)
            ->where(['card_id' => $cardId])
            ->field("FROM_UNIXTIME(create_time, '%Y-%m') as month,count(*) as count")
            ->group("date_format(FROM_UNIXTIME(create_time, '%Y-%m-%d %H:%i:%S') ,  '%Y-%m')")->select()->toArray();
        $monthpay = $this->cardOrderModel->cache(900)
            ->where(['card_id' => $cardId, 'status' => 1])
            ->field("FROM_UNIXTIME(create_time, '%Y-%m') as month,count(*) as count")
            ->group("date_format(FROM_UNIXTIME(create_time, '%Y-%m-%d %H:%i:%S') ,  '%Y-%m')")->select()->toArray();
        $monthno = $this->cardOrderModel->cache(900)
            ->where(['card_id' => $cardId, 'status' => 0])
            ->field("FROM_UNIXTIME(create_time, '%Y-%m') as month,count(*) as count")
            ->group("date_format(FROM_UNIXTIME(create_time, '%Y-%m-%d %H:%i:%S') ,  '%Y-%m')")->select()->toArray();
        $monthall = array_column($monthall, 'count', 'month');
        $monthpay = array_column($monthpay, 'count', 'month');
        $monthno = array_column($monthno, 'count', 'month');
        $monthallData = array_merge($monthData, $monthall);
        $monthpayData = array_merge($monthData, $monthpay);
        $monthnoData = array_merge($monthData, $monthno);
        $data = [
            'month' => json_encode(array_keys($monthData)),
            'name' => json_encode(['总下单量','已支付','未支付']),
            'data'=>[
                'all' => ['name' => '总下单量', 'data' => json_encode(array_values($monthallData))],
                'pay' => ['name' => '已支付', 'data' => json_encode(array_values($monthpayData))],
                'no' => ['name' => '未支付', 'data' => json_encode(array_values($monthnoData))],]

        ];
        $this->assign('data', $data);
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 生成卡券号
     */
    public function buildCardKey()
    {
        set_time_limit(0);
        $cardId = $this->request->param('card_id/d');
        $cardInfo = $this->cardModel->find($cardId);
        $map['card_id'] = $cardId;
        $buildCount = $this->cardItemModel->where($map)->count(); //已生成卡券数量
        if (($cardInfo['quantity'] - $buildCount) >= 300) {
            $batch = 300;
        } else {
            $batch = ($cardInfo['quantity'] - $buildCount);
        }
        if ($buildCount < $cardInfo['quantity']) {
            $dataList = [];
            for ($i = 0; $i < $batch; $i++) {
                $dataList[] = [
                    'card_id' => $cardInfo['card_id'],
                    'card_key' => $this->cardItemModel->getCardKey(),
                ];
            }
            if ($dataList) {
                $this->cardItemModel->saveAll($dataList);
            }
            $this->success('已生成[' . $batch . '],转向下一批！', url('buildCardKey', ['card_id' => $cardId]));
        } else {
            $this->success('生成完毕！', url('index'));
        }
    }

    /**
     * 查看卡券号
     */
    public function viewCardKey()
    {
        $map = [];
        $query = [];
        $type = $this->request->param('type', 'unused');
        $cardId = $this->request->param('card_id/d');
        $cardInfo = $this->cardModel->where('card_id', $cardId)->find();
        $query['type'] = $type;
        $map['t1.card_id'] = $cardId;
        $query['card_id'] = $cardId;
        $cardKey = $this->request->param('card_key');
        $query['card_key'] = $cardKey;
        if (!empty($cardKey)) {
            $map['card_key'] = $cardKey;
        }
        $list = $this->cardItemModel->getPageList($type, 12, $map, $query);
        $this->assign('list', $list);
        $this->assign('query', $query);
        $this->assign('cardInfo', $cardInfo);
        return $this->fetch();
    }

    /**
     * 删除卡券号
     */
    public function delItem()
    {
        $itemId = $this->request->param('item_id/d');
        $map['item_id'] = $itemId;
        if ($this->cardItemModel->where($map)->where('is_use', 1)->find()) {
            $this->error('使用过优惠券不允许删除！');
        }
        $this->cardItemModel->delData($itemId);
        $this->success('删除成功！');
    }
}